"""简单时序数据缓冲器

根据时间戳对数据进行排序，然后合并为有序列表
"""

import time
from typing import List, Dict, Any, Callable, Optional
from loguru import logger


class SimpleTimeBuffer:
    """简单时序缓冲器
    
    功能：
    1. 收集带时间戳的数据
    2. 按时间戳排序
    3. 合并为有序列表
    4. 定期刷新到存储
    """
    
    def __init__(self, flush_interval: int = 30):
        """初始化
        
        Args:
            flush_interval: 刷新间隔（秒）
        """
        self.flush_interval = flush_interval
        self._data_buffer: List[Dict[str, Any]] = []
        self._last_flush_time = time.time()
        self._flush_callback: Optional[Callable] = None
        
        logger.info(f"简单时序缓冲器初始化完成: flush_interval={flush_interval}s")
    
    def set_flush_callback(self, callback: Callable[[str, List[Dict]], None]):
        """设置刷新回调函数"""
        self._flush_callback = callback
        logger.info("回调函数已设置")
    
    def add_data(self, data_point: Dict) -> None:
        """添加数据点到缓冲区
        
        Args:
            data_point: 包含timestamp、session_id、data等字段的数据点
        """
        try:
            # 基本数据验证
            if not isinstance(data_point, dict):
                logger.error("数据点必须是字典类型")
                return
                
            if 'timestamp' not in data_point:
                logger.error("数据点缺少timestamp字段")
                return
                
            if 'session_id' not in data_point:
                logger.warning("数据点缺少session_id字段，使用默认值")
                data_point['session_id'] = 'default_session'
            
            self._data_buffer.append(data_point)
            logger.debug(f"添加数据点: session_id={data_point.get('session_id')}, timestamp={data_point.get('timestamp')}")
            
            # 检查是否需要刷新
            current_time = time.time()
            if current_time - self._last_flush_time >= self.flush_interval:
                logger.debug(f"达到刷新间隔 ({self.flush_interval}s)，触发自动刷新")
                self._flush_data()
                
        except Exception as e:
            logger.error(f"添加数据点时发生错误: {e}")
            # 不抛出异常，避免影响上层调用
    
    def _flush_data(self):
        """刷新数据 - 按session_id分组，然后按时间戳排序并调用回调"""
        if not self._data_buffer:
            logger.debug("缓冲区为空，跳过刷新")
            return
        
        try:
            # 按session_id分组数据
            session_groups = {}
            for data_point in self._data_buffer:
                session_id = data_point.get('session_id', 'default_session')
                if session_id not in session_groups:
                    session_groups[session_id] = []
                session_groups[session_id].append(data_point)
            
            # 为每个session分别处理数据
            for session_id, session_data in session_groups.items():
                # 按时间戳排序该session的数据
                sorted_data = sorted(session_data, key=lambda x: x['timestamp'])
                
                # 调用回调函数处理该session的数据
                if self._flush_callback:
                    self._flush_callback(session_id, sorted_data)
                    logger.info(f"数据已刷新: session_id={session_id}, count={len(sorted_data)}")
                else:
                    logger.warning("回调函数未设置，数据无法刷新")
            
            # 清空缓冲区
            self._data_buffer.clear()
            self._last_flush_time = time.time()
            
        except Exception as e:
            logger.error(f"刷新数据时发生错误: {e}")
            # 发生错误时仍然清空缓冲区，避免数据积累
            self._data_buffer.clear()
            self._last_flush_time = time.time()
    
    def force_flush(self):
        """强制刷新缓冲区"""
        try:
            logger.info("执行强制刷新")
            self._flush_data()
        except Exception as e:
            logger.error(f"强制刷新时发生错误: {e}")
    
    def cleanup(self):
        """清理资源"""
        self._flush_data()  # 最后刷新一次
        logger.info("简单时序缓冲器已清理")